// 评论回复数据库
const { DataTypes } = require("sequelize");
const sequelize = require("../config/sequelize");
const User = require("./user");
const Post = require("./post");

const Like = sequelize.define(
  "Like",
  {},
  {
    sequelize: sequelize,
    tableName: "like",
    underscored: true,
  }
);
Like.belongsTo(User, {
  constraints: false,
  foreignKey: "userId",
  as: "user",
});

Like.belongsTo(Post, {
  constraints: false,
  foreignKey: "postId",
  as: "post",
});

Like.afterCreate(async (like) => {
  // 文章点赞数+1
  await Post.increment({ likeNum: 1 }, { where: { id: like.postId } });
});
Like.afterDestroy(async (like) => {
  // 文章点赞数-1
  await Post.increment({ likeNum: -1 }, { where: { id: like.postId } });
});

module.exports = Like;
